package com.demo.config;

import com.demo.component.srv.Receiver;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.MessageListenerContainer;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.amqp.rabbit.transaction.RabbitTransactionManager;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Author:  Hardy
 * Date:    2018/7/18 20:05
 * Description:
 **/
@Configuration
public class RabbitConfig {

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitTransactionManager rabbitTransactionManager(ConnectionFactory connectionFactory) {
        return new RabbitTransactionManager(connectionFactory);
    }

    @Bean
    public Queue queue() {
        return new Queue("test", true, false, false);
    }

    @Bean
    public Exchange exchange() {
        return new DirectExchange("test", true, false);
    }

    @Bean
    public Binding binding(Queue queue, Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("test-key").noargs();
    }


    @Bean
    public MessageListenerAdapter listenerAdapter(MessageConverter messageConverter,
                                                  Receiver receiver) {
        MessageListenerAdapter adapter = new MessageListenerAdapter(receiver, "message");
        adapter.setMessageConverter(messageConverter);
        return adapter;
    }

    @Bean
    public MessageListenerContainer container(ConnectionFactory connectionFactory,
                                              MessageListenerAdapter listenerAdapter,
                                              Queue queue) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setMessageListener(listenerAdapter);
        container.setMaxConcurrentConsumers(1);
        container.setQueues(queue);
        return container;
    }
}
